local util = require "util"
local conf = require "conf"
local require = require
local setmetatable = setmetatable
local error = error
local json = require 'cjson'
local table = table
local ngx = ngx
local os = os
local string = string
local tonumber = tonumber
local math = math
local pairs = pairs
local io = io
local type = type
package.cpath = "/opt/xyitech/jieyan-backend-production/xbit/?.so"
local xbit = require("xbit")
package.cpath = "/usr/nginx/?.so;;"
local json = require 'cjson'
module(...)

_VERSION = '0.1'
 _int32_t = 0
 _int16_t = 1
 _float = 2
 _uint32_t = 4
 _uint16_t = 5
 _uint8_t = 6
 _int8_t = 7
_jieyan_takeoff_admin = 107


_message = {
    ["1"] = "抱歉，收件人员不在站点内，请稍后再发起审核或联系收件人",
    ["2"] = "抱歉，收件站点内现在很忙，无法收货，请稍后再发起审核或联系收件人",
    ["3"] = "抱歉，收件站点场地条件不允许，请稍后再发起审核或联系收件人",
    ["4"] = "抱歉，收件站点当前天气条件较差，请稍后再发起审核或联系收件人",
    ["5"] = "抱歉，请稍后再发起审核或联系收件人"
}
--type = {bill, notice, warning}
-- state = {
--     0= 已读
--     1= 未读
--     2= 已结算
--     3= 通过
--     4= 拒绝
--     5= 已过期
-- }
function createController(user, args)
    local res = create(user, args)    
    local db = conf.get_mysql()

    if not res or res.affected_rows < 1 then
        ngx.print(json.encode({
            err = 1,
            msg = '创建失败'
        }))
        ngx.exit(200)
    else
        local insert_id = res.insert_id
        if insert_id < 1 then
            res = db:query("SELECT LAST_INSERT_ID() AS insert_id")
            if res and res[1] and res[1].insert_id then
                insert_id = res[1].insert_id
            end
        end
        ngx.print(json.encode({
            err = 0,
            id = insert_id,
            msg = '创建成功'
        }))
        ngx.exit(200)
    end
end

function create(user, args)
    local mtype, body, header, params, to_uid, state, aid = args.type, args.body, args.header, args.params, args.to_uid, args.state, args.aid
    local red = conf.get_redis()
    local db = conf.get_mysql()
    local vals = {}
    if mtype then
        vals[#vals + 1] = "type = " .. ngx.quote_sql_str(mtype)
    end
    if body then
        vals[#vals + 1] = "body = " .. ngx.quote_sql_str(body)
    end
    if aid then
        vals[#vals + 1] = "aid = " .. ngx.quote_sql_str(aid)
    else
        vals[#vals + 1] = "aid = " .. ngx.quote_sql_str(user.aid)
    end

    vals[#vals + 1] = "uid = " .. ngx.quote_sql_str(user.id)
    
    if header then
        vals[#vals + 1] = "header = " .. ngx.quote_sql_str(header)
    end

    if params then
        vals[#vals + 1] = "params = " .. ngx.quote_sql_str(params)
    end

    if to_uid then
        vals[#vals + 1] = "to_uid = " .. ngx.quote_sql_str(to_uid)
    end
    if state then
        vals[#vals + 1] = "state = " .. ngx.quote_sql_str(state)
    end
    vals[#vals + 1] = "create_time = " .. os.time()
    vals[#vals + 1] = "update_time = " .. os.time()

    local res = db:query("INSERT INTO `message` SET " .. table.concat(vals, ","))
    return res
end


function createCancleScheduleMessage(user, args)
    args.type = "notice"
    local date = util.date(args.schedule_date)
    args.body = "[用户: " .. user.name .. "] 将" .. date .. "日，航班[" .. args.flight_number .. "] 由"
    if tonumber(args.opt) == 1 then
        args.body = args.body .. "计划改为取消"
    else
        args.body = args.body .. "取消改为计划"
    end
    args.header = "航班变更"
    args.state = 1
    local res = create(user, args)
    return res
end

function createOrderConfirmMessage(user, args)
    local sms = require 'sms'
    ngx.log(ngx.ERR, json.encode(args))
    local time = os.date("%H:%M:%S", os.time()) .. ""
    ngx.log(ngx.ERR, time)
    if args.phone and args.phone ~= "" and tonumber(args.phone) ~= 0 then
        local params = {
            ["signname"] = "捷雁云",
            ["code"] = "SMS_80030097",
            ["paramstring"] = json.encode({["name"] = user.name, ["time"] = time, ["seria_no"] = args.serial_no, ["sname"] = args.sname, ["ename"] = args.ename}),
            ["recnum"] = tonumber(args.phone),
        }
        
        local code = sms.send(params)
    end
end

function createTakeoffApproveMessage(user, args)
    local sms = require 'sms'
    ngx.log(ngx.ERR, json.encode(args))
    local time = os.date("%H:%M:%S", os.time()) .. ""
    ngx.log(ngx.ERR, time)
    if args.phone and args.phone ~= "" and tonumber(args.phone) ~= 0 then
        local params = {
            ["signname"] = "捷雁云",
            ["code"] = "SMS_70590290",
            ["paramstring"] = json.encode({["username"] = user.name, ["time"] = time, ["seria_no"] = args.serial_no, ["sname"] = args.sname, ["ename"] = args.ename,}),
            ["recnum"] = tonumber(args.phone),
        }
        
        local code = sms.send(params)
    end

    local message = "[用户: " .. user.name .. "] 申请起飞： 运单编号[" .. args.serial_no .. "], 飞行起点[" .. args.sname .. "]、终点[" .. args.ename.. "]。"
    args.type = "takeoff"
    args.body = message .. "请在10分钟以内确认"
    args.params = json.encode({["flight_number"]=args.flight_number, ["serial_no"]=args.serial_no, ["id"]=args.id})
    args.header = "申请起飞"
    args.state = 1
    local res = create(user, args)
    return res
end

function getMessageWithOrderId(args)
    local db = conf.get_mysql()
    local time = os.time() - 600
    local sql = "SELECT id, create_time FROM `message` WHERE type = 'takeoff' AND (state =1 or state =0) AND params like '%\"id\":\"" .. args.id .."\"%' AND create_time > " .. time
    ngx.log(ngx.ERR, sql)
    local res = db:query(sql)
    return res or {}
end

function listController(user, args)
    local res = list(user, args)
        if not res then
        ngx.print(json.encode({ 
            err = 1,
            msg = '未找到相应的订单'
        }))
        ngx.exit(200)
    else
        ngx.print(json.encode({
            err = 0,
            msg = res
        }))
        ngx.exit(200)
    end
end

function list(user, args)
    local db = conf.get_mysql()
    local sql = "SELECT * FROM `message` WHERE to_uid = " .. user.id
    if args.type then
        sql = sql .. " AND `message`.type = " .. ngx.quote_sql_str(args.type)
    end
    if args.id then
        sql = sql .. " AND `message`.id = " .. args.id
    end
    if args.order_id then
        sql = sql .. " AND `message`.params like '%\"id\":\"" .. args.order_id .."\"%'"
    end
    if args.state then
        sql = sql .. " AND `message`.state = " .. ngx.quote_sql_str(args.state)
    end
    if args.page_no and args.page_size then
        sql = sql .. " ORDER BY id DESC LIMIT " .. (args.page_no * args.page_size) .. "," .. args.page_size
    end
    -- ngx.log(ngx.ERR, sql)
    local res = db:query(sql)
    return res
end

function updateController(user, args)
    if not args.id or not args.state then
        ngx.print(json.encode({
            err = 1,
            msg = '参数不正确'
        }))
        ngx.exit(200)
    end
    local res, state = update(user, args)
        if not res then
        ngx.print(json.encode({ 
            err = 1,
            msg = '未找到相应的订单'
        }))
        ngx.exit(200)
    else
        ngx.print(json.encode({
            err = 0,
            msg = "成功",
            state = state
        }))
        ngx.exit(200)
    end
end
--spoint_admin_status,spoint_admin_status 1通过，2拒绝，3待定
function update(user, args)
    local id, state = tonumber(args.id), tonumber(args.state)
    local err = nil
    local msg = ""
    local db = conf.get_mysql()
    local vals = {}

    local message = detail(user, {["id"] = id})
    if not message or #message == 0 then
        return nil
    end
    message = message[1]
    ngx.log(ngx.ERR, json.encode(message))
    local params = json.decode(message.params)

    if message.type == "takeoff" then
        local order =  require "order"
        if os.time() - tonumber(message.create_time) > 300 then
            state = 5
        else
            local orderDetail = order.detail(user, {["id"] = params.id})
            if orderDetail and orderDetail[1] then
                if state == 3 then
                    if message.to_uid == _jieyan_takeoff_admin then
                        local res, err = order.update(user, {["state"] = 6, ["id"] = params.id, ["jieyan_admin_status"] = 1 , ["jieyan_admin_uid"] = user.id})
                    else
                        if orderDetail[1].spoint_admin_status == 0 then
                            local res, err = order.update(user, {["state"] = 7, ["id"] = params.id, ["spoint_admin_status"] = 1, ["spoint_admin_uid"] = user.id})
                        end
                    end
                    ngx.log(ngx.ERR, err)
                elseif state == 4 then
                    if orderDetail[1].state ~= 1 then
                        if message.to_uid == _jieyan_takeoff_admin then
                            local res, err = order.update(user, {["state"] = 1, ["id"] = params.id, ["jieyan_admin_status"] = 2, ["jieyan_admin_uid"] = user.id})
                        else
                            if orderDetail[1].spoint_admin_status == 0 then
                                local orderArgs = {["id"] = params.id, ["spoint_admin_status"] = 2, ["state"] = 1, ["remark"] = _message[args.msgId..""], ["spoint_admin_uid"] = user.id}
                                -- if orderDetail[1].spoint_admin_status == 3 then
                                    -- orderArgs.spoint_admin_status = 2
                                    -- orderArgs.state = 1
                                -- end
                                ngx.log(ngx.ERR, _message[args.msgId..""])
                                ngx.log(ngx.ERR, json.encode(orderArgs))
                                local res, err = order.update(user, orderArgs)
                            end
                        end
                    end
                end
            end
        end
    end
    local stateChangeTime = os.time()
    vals[#vals + 1] = "state = " .. state
    vals[#vals + 1] = "update_time = " .. stateChangeTime
        
    local res, err = db:query("UPDATE `message` SET " .. table.concat(vals, ",") .. " WHERE id = " .. id) --.. " AND aid = " .. aid)
    return res, state
end

function detailController(user, args)
    local res = detail(user, args)
    if res and res[1] then
        if tonumber(res[1].state) == 0 then
            local res = update(user, {["id"] = args.id, ["state"] = 1})
        end
    end
    if not res or not res[1] then
        ngx.print(json.encode({
            err = 1,
            msg = '未找到相应的消息'
        }))
        ngx.exit(200)
    else
        ngx.print(json.encode({
            err = 0,
            msg = res[1],
            osTime = os.time()
        }))
        ngx.exit(200)
    end
end

function detail(user, args)
    local db = conf.get_mysql()
    local sql = "SELECT * FROM `message` WHERE id = " .. args.id .. " AND to_uid = " ..  user.id
    -- ngx.log(ngx.ERR, sql)
    local res = db:query(sql)
    return res
end


function sendPhoneDataUsage(args)
    local http = require 'http'
    --local phones = {17288109323, 17288109378, 17288109377}
    local plane_data_usage = require 'plane_data_usage'
    local res,count = plane_data_usage.search()
    local phones = {}
    
    --local uids = {37, 1, 99}
    --local res = {}
    local msg = ""
    

    for k,v in pairs(res) do
        if res[k] then
            phones[k] = res[k].phone_id
        end
    end

    for k,v in pairs(phones) do 
        local arg = res[k]
        local ok,code,_,_,body = http:request{
            url = "http://www.enjoyvalley.com/queryLL.ashx",
            body = "phone=" .. v,
            timeout = 6000,
            method = "POST",
        }
        if code == 200 then
            body = json.decode(body)
            msg = msg .. "流量卡： " .. v .. "<br /><br />"
            if body.percent then
                arg.percent = body.percent
            end
            if body.total then
                arg.total = body.total
            end
            if body.already then 
                arg.already = body.already
            end
            if body.total_next then   
                arg.total_next = body.total_next
            end
            arg.phone_id = v
            plane_data_usage.update(arg)  
            msg = msg .. "当前已使用流量百分比：" .. arg.percent .. "<br />当月总流量：" .. arg.total .. " <br />当月已使用：" .. arg.already .. " <br />下月总流量:" .. arg.total_next      
        end
    end
   
    ngx.print(json.encode({
        err = 0,
        msg = msg
    }))
    ngx.exit(200)

end

function systemMessage(user, args)
    local db = conf.get_mysql()
    local sql = "SELECT * FROM `message` WHERE to_uid = 0"
    if args.type then
        sql = sql .. " AND `message`.type = " .. ngx.quote_sql_str(args.type)
    end
    if args.id then
        sql = sql .. " AND `message`.id = " .. args.id
    end
    if args.order_id then
        sql = sql .. " AND `message`.params like '%\"id\":\"" .. args.order_id .."\"%'"
    end
    if args.state then
        sql = sql .. " AND `message`.state = " .. ngx.quote_sql_str(args.state)
    end

    if args.create_time then
        sql = sql .. " AND `message`.create_time > " .. args.create_time
    end

    if args.page_no and args.page_size then
        sql = sql .. " ORDER BY id DESC LIMIT " .. (args.page_no * args.page_size) .. "," .. args.page_size
    end
    -- ngx.log(ngx.ERR, sql)
    local res = db:query(sql)
    return res
end

function systemMessageController(user, args)
    local res = systemMessage(user, args)
        if not res then
        ngx.print(json.encode({ 
            err = 1,
            msg = '未找到相应的订单'
        }))
        ngx.exit(200)
    else
        ngx.print(json.encode({
            err = 0,
            msg = res
        }))
        ngx.exit(200)
    end
end

function createUpdateMessage(user, args)
    local sms = require 'sms'
    -- ngx.log(ngx.ERR, json.encode(args))
    -- local time = os.date("%H:%M:%S", os.time()) .. ""
    ngx.log(ngx.ERR, time)
    if args.phone and args.phone ~= "" and tonumber(args.phone) ~= 0 then
        local params = {
            ["signname"] = "捷雁云",
            ["code"] = "SMS_84610016",
            ["paramstring"] = json.encode({}),
            ["recnum"] = tonumber(args.phone),
        }
        
        local code = sms.send(params)
    end
end

function sendUpdateMessage(user, args)
    local userModule = require 'user'
     local user = conf.userDetail({["id"]= 1})
    local acceptUsers = userModule.search(user, {["role_id"] = 3})
    acceptUsers = {}
    table.insert(acceptUsers, {["phone"] = 15868191390})
    local url = "http://jieyan.xyitech.com/static/jetgo2.0airwayprod.apk"
    for k,v in pairs(acceptUsers) do
        createUpdateMessage(user, {["phone"] = v.phone})
    end
    ngx.print(json.encode({
            err = 0,
            msg = "发送成功"
        }))
        ngx.exit(200)
end

function default(args)
    local conf = require "conf"
    local user = conf.parse_token(args, "message")
    if args.action == 'create' then
        createController(user, args)
    elseif args.action == 'list' then
        listController(user, args)
    elseif args.action == 'update' then
        updateController(user, args)
    elseif args.action == 'detail' then
        detailController(user, args)
    elseif args.action == 'systemMessage' then
        systemMessageController(user, args)
    elseif args.action == 'sendPhoneDataUsage' then
        sendPhoneDataUsage(user, args)
    elseif args.action == 'sendUpdateMessage' then
        sendUpdateMessage(user, args)
    end
end

local class_mt = {
    __newindex = function (table, key, val)
        error('attempt to write to undeclared variable "' .. key .. '"')
    end
}
setmetatable(_M, class_mt)